<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Document</title>
</head>

<body>
	<script>
		var old = {
			name: "old",
			attr: {
				age: 18,
				sex: "man"
			},
			title: ["M1", "P6"]
		};

		// 判断数据类型
		function getType(attr) {
			let type = Object.prototype.toString.call(attr);
			let newType = type.substr(8, type.length - 9);
			return newType
		};
		function stringify(obj) {
			// 如果是非object类型，就直接返回原值的string
			if (typeof obj != 'object' || getType(obj) === null) {
				return String(obj)
			}
			let json = []
			let arr = obj ? getType(obj) == 'Array' : false;
			for (let key in obj) {
				if (obj.hasOwnProperty(key)) {
					let item = obj[key];

					if (getType(obj) == 'Object') {
						item = stringify(item)

					}
					json.push((arr ? '"' : '"' + key + '": "') + String(item) + '"');
				}
			}
			console.log(arr, String(json));
			return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}")

		}
		let res = stringify(old)
		console.log(res)
	</script>
</body>

</html>